/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package graphic;

import UML.ClassDiagram;
import include.fxml.SlyumFX;
import javafx.event.EventHandler;
import javafx.scene.input.DragEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.Pane;

/**
 *
 * @author David
 */
public class DiagramPane extends Pane {
  
  ClassDiagram classDiagram;
  
  public DiagramPane(ClassDiagram classDiagram){
    initialize(classDiagram);
  }
  
  private void initialize(ClassDiagram classDiagram){
    
    getStyleClass().add("diagram");
    registerEvents();
    
    setClassDiagram(classDiagram);
  }
  
  private void registerEvents(){
    setOnDragOver(new EventHandler<DragEvent>() {

      @Override
      public void handle(DragEvent de) {
        
        if (de.getDragboard().hasString()){
          Factory f = SlyumFX.getFactoryByType(de.getDragboard().getString());
          
          if (f != null) {
            de.acceptTransferModes(TransferMode.ANY);
            f.setTranslateX(de.getX() - f.getBoundsInParent().getWidth() / 2);
            f.setTranslateY(de.getY() - f.getBoundsInParent().getHeight() / 2);
          }
        }
        
        de.consume();
      }
    });
    
    setOnDragEntered(new EventHandler<DragEvent>() {

      @Override
      public void handle(DragEvent de) {
        if (de.getDragboard().hasString()){
          Factory f = SlyumFX.getFactoryByType(de.getDragboard().getString());

          if (f != null) {
            de.acceptTransferModes(TransferMode.ANY);
            getChildren().add(f);
          }
        }
        de.consume();
      }
    });
    
    setOnDragExited(new EventHandler<DragEvent>() {

      @Override
      public void handle(DragEvent de) {
        if (de.getDragboard().hasString()){
          Factory f = SlyumFX.getFactoryByType(de.getDragboard().getString());

          if (f != null) {
            getChildren().remove(f);
          }
        }
        de.consume();
      }
    });
    
    setOnDragDropped(new EventHandler<DragEvent>() {
      
      @Override
      public void handle(DragEvent de) {
        boolean success = false;
        if (de.getDragboard().hasString()){
          Factory f = SlyumFX.getFactoryByType(de.getDragboard().getString());

          if (f != null) {
            success = true;
            getChildren().remove(f);
            f.create();
          }
        }
        
        de.setDropCompleted(success);
        de.consume();
      }
    });
  }
  
  public ClassDiagram getClassDiagram(){
    return classDiagram;
  }
  
  public void setClassDiagram(ClassDiagram classDiagram){
    
    if (classDiagram == null)
      throw new IllegalArgumentException("Class diagram cannot be null.");
    
    this.classDiagram = classDiagram;
  }
}
